<template>
  <div class="app-container">
    <el-form
      :model="params"
      ref="goodsForm"
      size="mini"
      :inline="true"
      class="demo-form-inline"
    >
      <el-form-item prop="PT_TypeId">
        <el-select
          clearable
          placeholder="选择商品分类"
          v-model="params.PT_TypeId"
        >
          <el-option
            :key="cate.id"
            v-for="cate in categoryList"
            :label="cate.pType_Name"
            :value="cate.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="KeyWord">
        <el-input
          v-model="params.KeyWord"
          clearable
          placeholder="请输入商品编号/名称"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" type="primary" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>
    <div style="margin-bottom: 8px">
      <el-button
        size="mini"
        icon="el-icon-plus"
        type="success"
        @click="handleAdd"
        >新增商品</el-button
      >
    </div>

    <el-table v-loading="loading" :data="goodsList" border style="width: 100%">
      <el-table-column align="center" type="index" width="50"></el-table-column>
      <el-table-column align="center" prop="pT_ImgPath" label="商品图片">
        <template slot-scope="scope">
          <el-image
            style="width: 40px; height: 40px"
            :src="scope.row.pT_ImgPath"
            :preview-src-list="[scope.row.pT_ImgPath]"
          >
          </el-image>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        prop="pT_Name"
        label="商品名称"
      ></el-table-column>
      <el-table-column
        align="center"
        prop="pT_Code"
        label="商品编码"
      ></el-table-column>
      <el-table-column
        align="center"
        prop="pT_TypeName"
        label="商品分类"
      ></el-table-column>
      <el-table-column
        align="center"
        prop="stockNumner"
        label="商品库存"
      ></el-table-column>
      <el-table-column
        align="center"
        prop="pT_Unit"
        label="商品单位"
      ></el-table-column>
      <el-table-column
        align="center"
        prop="pT_Price"
        label="商品价格"
      ></el-table-column>
      <el-table-column
        align="center"
        prop="pT_DisPrice"
        label="商品特价"
      ></el-table-column>
      <el-table-column align="center" prop="address" label="操作">
        <template slot-scope="scope">
          <el-button-group>
            <el-button
              type="info"
              icon="el-icon-edit"
              @click="handleEdit(scope.row.id)"
            ></el-button>
            <el-button type="danger" @click="handleDelete(scope.row)"
              ><i class="el-icon-delete"></i
            ></el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      class="pagenation"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="params.page"
      :page-sizes="[5, 10, 15, 20]"
      :page-size="5"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>

    <!-- 新增、修改的模态框 -->

    <el-dialog
      :title="isEdit ? '修改商品' : '新增商品'"
      :visible.sync="dialogFormVisible"
    >
      <el-form
        :model="addGooodsForm"
        :rules="rules"
        ref="addGooodsForm"
        size="mini"
        label-position="right"
        label-width="80px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="商品名称" prop="pT_Name">
              <el-input
                autocomplete="off"
                placeholder="请输入商品名称"
                v-model="addGooodsForm.pT_Name"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品分类" prop="pT_TypeId">
              <el-select
                clearable
                placeholder="选择商品分类"
                v-model="addGooodsForm.pT_TypeId"
              >
                <el-option
                  :key="cate.id"
                  v-for="cate in categoryList"
                  :label="cate.pType_Name"
                  :value="cate.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="商品价格" prop="pT_Price">
              <el-input
                placeholder="选择商品价格"
                autocomplete="off"
                v-model="addGooodsForm.pT_Price"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品单位" prop="pT_Unit">
              <el-input
                placeholder="输入商品单位"
                autocomplete="off"
                v-model="addGooodsForm.pT_Unit"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="商品特价">
              <el-input
                placeholder="请输入商品特价"
                autocomplete="off"
                v-model="addGooodsForm.pT_DisPrice"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品编码" prop="pT_Code">
              <el-input
                placeholder="请输入商品编码"
                autocomplete="off"
                v-model="addGooodsForm.pT_Code"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20"
          ><el-col :span="24">
            <el-form-item label="商品图片">
              <!-- 默认情况下 elemt的 图片上传是直接就把图片上传到服务器 
                   是不是会造成，很多无用上传啊  
              -->
              <el-upload
                class="avatar-uploader"
                action="#"
                :show-file-list="false"
                :http-request="handleImgShow"
                :on-success="handleAvatarSuccess"
              >
                <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload> </el-form-item
          ></el-col>
        </el-row>
        <el-row
          ><el-col :span="24">
            <el-form-item label="商品备注">
              <el-input
                :rows="4"
                type="textarea"
                placeholder="请输入备注内容"
                maxlength="120"
                show-word-limit
                v-model="addGooodsForm.pT_Remarks"
              >
              </el-input>
            </el-form-item> </el-col
        ></el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="isEdit" type="primary" @click="handleGoodsSave"
          >保 存</el-button
        >
        <el-button v-else type="primary" @click="handleGoodsSubmit"
          >确 定</el-button
        >
        <el-button @click="handleCancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  QueryProductList,
  ProductUploadFile,
  CreateProduct,
  DeleteProduct,
  GetProductInfo,
  UpdateProduct,
} from "../../api/goods";
import { mapActions, mapState } from "vuex";

export default {
  data() {
    return {
      loading: false,
      dialogFormVisible: false,
      imageUrl: null, // 图上上传后返回地址
      params: {
        PT_TypeId: "",
        ShopId: "",
        KeyWord: "",
        page: 1,
        size: 5,
      },
      addGooodsForm: {
        //提交商品需要我们传递的数据
        pT_Name: "",
        pT_TypeId: null,
        pT_Price: null,
        pT_DisPrice: 0,
        pT_Code: "",
        pT_ImgPath: "",
        pT_Unit: "",
        pT_Remarks: "",
        shopId: 1,
      },

      rules: {
        pT_Name: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        pT_TypeId: [
          { required: true, message: "请选择商品类型", trigger: "blur" },
        ],
        pT_Price: [
          { required: true, message: "请输入商品价格", trigger: "blur" },
        ],
        pT_Unit: [
          { required: true, message: "请输入商品单位", trigger: "blur" },
        ],
        pT_Code: [
          { required: true, message: "请输入商品编码", trigger: "blur" },
        ],
      },
      goodsList: [],
      total: 0,
      isEdit: false, //控制编辑
      isUpdateImg: false, // 判断编辑是否修改了 图片
    };
  },
  computed: {
    ...mapState("goods", ["categoryList"]),
    ...mapState("user", ["shopId"]),
  },
  mounted() {
    this.addGooodsForm.shopId = this.shopId;
    this.fetchGoodsList();
    this.fetchCategory({
      size: 10000,
      page: 1,
    });
  },
  methods: {
    ...mapActions("goods", ["fetchCategory"]),
    async fetchGoodsList() {
      this.loading = true;
      let { data } = await QueryProductList(this.params);
      this.goodsList = data.dataSource;
      this.total = data.totalCount; //查询总数
      this.loading = false;
    },
    handleSizeChange(size) {
      this.params.size = size;
      this.params.page = 1;
      this.fetchGoodsList();
    },
    handleCurrentChange(page) {
      //分页
      this.params.page = page;
      this.fetchGoodsList();
    },
    handleQuery() {
      //还原分页
      this.params.page = 1;
      this.fetchGoodsList();
    },
    handleReset() {
      this.$refs.goodsForm.resetFields();
      this.params.page = 1;
      this.params.size = 5;
      this.fetchGoodsList();
    },
    handleGoodsSubmit() {
      //触发商品提交
      //处理商品提交
      this.$refs.addGooodsForm.validate(async (vaild) => {
        if (vaild) {
          //先上传商品
          try {
            let { data } = await CreateProduct(this.addGooodsForm);
            if (data) {
              //图片上传
              let result = await ProductUploadFile(
                {
                  ShopId: this.addGooodsForm.shopId,
                  ProductId: data,
                },
                this.file
              );

              this.$message({
                message: result.message,
                type: "success",
              });

              this.handleQuery();
            }
          } catch (error) {
            this.$message.error(error);
          }

          this.dialogFormVisible = false;
        }
      });
    },
    handleAdd() {
      this.dialogFormVisible = true;
    },
    handleAvatarSuccess() {},
    handleImgShow({ file }) {
      // 如何放到 img标签上显示 ，把文件对象转成base64
      // Filereader
      let fileObj = new FileReader();
      fileObj.readAsDataURL(file);
      this.file = file; //把file放到组建的实例上，并且不会被劫持
      fileObj.onload = ({ target }) => {
        this.imageUrl = target.result;
        this.isUpdateImg = true;
      };
    },
    handleDelete({ id, pT_Name }) {
      //删除商品
      this.$confirm(`此操作将删除 ${pT_Name}, 是否继续?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(async () => {
        let { message } = await DeleteProduct({ id });
        this.$message({
          message,
          type: "success",
        });
        this.fetchGoodsList();
      });
    },
    async handleEdit(id) {
      //编辑商品
      this.editId = id; //缓存用户编辑的那个id
      this.isEdit = true;
      this.dialogFormVisible = true;
      let loading = "";
      setTimeout(() => {
        loading = this.$loading({
          lock: true,
          text: "Loading",
          spinner: "el-icon-loading",
          background: "rgba(0, 0, 0, 0.9)",
        });
      }, 0);

      let { data } = await GetProductInfo({ id });

      for (let key in this.addGooodsForm) {
        this.addGooodsForm[key] = data[key];
      }
      this.imageUrl = data.pT_ImgPath;

      loading.close();
    },
    handleGoodsSave() {
      this.$refs.addGooodsForm.validate(async (vaild) => {
        let { data } = await UpdateProduct({
          ...this.addGooodsForm,
          id: this.editId,
        });

        if (this.isUpdateImg) {
          let result = await ProductUploadFile(
            {
              ShopId: this.addGooodsForm.shopId,
              ProductId: this.editId,
            },
            this.file
          );
        } //判断用户是不是修改了 图片

        this.$message({
          message: "更新成功！",
          type: "success",
        });

        this.handleQuery();
        this.resetGoodsForm()
      });
    },
    handleCancel(){
        this.resetGoodsForm()
    },
    resetGoodsForm() {
      this.dialogFormVisible = false;
      //更新后的还原操作
      this.addGooodsForm = {
        pT_Name: "",
        pT_TypeId: null,
        pT_Price: 0,
        pT_DisPrice: 0,
        pT_Code: "",
        pT_ImgPath: "",
        pT_Unit: "",
        pT_Remarks: "",
        shopId: 1,
      };
      this.imageUrl = "";
      this.isUpdateImg = false;
      
    },
  },
};
</script>

<style scoped>
</style>

